<template>
  <div class="purchase-list-layout role-layout">
    <crumbList :navList="navList"></crumbList>
    <div class="purchase-content role-content">
      <div class="purchase-table role-table">
        <div class="purchase-item">
          <el-form ref="searchData" :model="searchData" class="clearfix">
            <el-form-item class="principalItem">
              <el-input v-model="searchData.name" placeholder="账号"></el-input>
            </el-form-item>
            <el-form-item class="itemButton">
              <el-button type="primary" @click="search">查询</el-button>
              <el-button type="primary" @click="reset">重置</el-button>
              <el-button type="primary" class="addItem" @click="accountDialog = true">新增账号</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="purchase-table-list">
          <el-table :data="tableData" border>
            <el-table-column :label="item.label" v-for="(item,index) in table" :key="index" :width="item.name==='orderNum'?64:''">
              <template scope="scope">
                <span v-if="item.name === 'passwordName'">
                  <span v-show="!scope.row.edit" :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
                  <span v-show="scope.row.edit" title="修改密码">
                    <el-input v-model="scope.row.password" type="password" placeholder="输入密码"></el-input>
                  </span>
                </span>

                <span v-else-if="item.name === 'orderNum'">
                  <span :title="scope.row[item.name]">{{ scope.$index + 1 }}</span>
                </span>

                <span v-else-if="item.name === 'name'">
                  <span v-show="!scope.row.edit" :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
                  <span v-show="scope.row.edit" title="修改角色">
                    <el-select v-model="scope.row.roleId">
                      <el-option v-for="(item, index) in roleOptions" :label="item.name" :value="item.id" :key="index" :disabled="item.id === 1 ? true : false"></el-option>
                    </el-select>
                  </span>
                </span>

                <span v-else-if="item.name === 'isUsedName'">
                  <span v-show="!scope.row.edit" :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
                  <span v-show="scope.row.edit" title="修改状态">
                    <el-select v-model="scope.row.isUsed">
                      <el-option v-for="(item, index) in workOptions" :label="item.label" :value="item.value" :key="index"></el-option>
                    </el-select>
                  </span>
                </span>

                <span v-else :title="scope.row[item.name]">{{ scope.row[item.name] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template scope="scope">
                <el-button v-show='!scope.row.edit' type="primary" class="editBtn" @click='scope.row.edit = true' :disabled="scope.row.id === 1 ? true : false">修改</el-button>
                <el-button v-show='scope.row.edit' type="primary" class="editBtn" @click='handleUpdate(scope.$index, scope.row)'>完成</el-button>
                <el-button type="primary" class="deleteBtn" @click="remove(scope.$index, scope.row)" :disabled="scope.row.id === 1 ? true : false">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination layout="total, prev, pager, next, jumper"
                         @current-change="handleCurrentChange"
                         :current-page="page.pageNum"
                         :page-size="page.pageSize"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!--新增账号-->
    <el-dialog class="role-dialog" v-model="accountDialog" title="新增账号" @close="dialogFormClose('accountForm')" top="70px">
      <div>
        <el-form :model="accountForm" :rules="rules" ref="accountForm" label-width="20%" label-position="right">
          <el-form-item prop="loginName" label="用户名">
            <el-input v-model="accountForm.loginName"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input v-model="accountForm.password"></el-input>
          </el-form-item>
          <el-form-item prop="roleId" label="角色">
            <el-select v-model="accountForm.roleId">
              <el-option v-for="(item, index) in roleOptions" :label="item.name" :value="item.id.toString()" :key="index" :disabled="item.id === 1 ? true : false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isUsed" label="状态">
            <el-radio-group v-model="accountForm.isUsed">
              <el-radio-button v-for="item in workOptions" :label="item.value.toString()" :key="item.value">{{ item.label }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <div class="operationBtn">
            <el-button class="cancelBtn" @click="dialogFormClose('accountForm')">取消</el-button>
            <el-button class="nextBtn" @click="submitForm('accountForm')">提交</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import copyObject from '../../../utils/copyObject/copyObject'
  import ajax from '../../../utils/ajax/index'
  import getRoleName from './js/getRoleName'
  import workType from '../../../utils/changeType/workType' // 展示启用禁用状态
  import crumbList from '../../common/crumbList.vue'

  export default {
    data () {
      return {
        navList: [
          {name: '设置', path: ''},
          {name: '账号管理', path: ''}
        ],
        searchData: {
          loginName: ''
        },
        tableData: [
          {
            edit: false,
            orderNum: '1',
            loginName: '超级管理员',
            passwordName: '******',
            name: '1',
            isUsedName: '1',
            createTime: '2017-08-12'
          }
        ],
        table: [
          {label: '序号', name: 'orderNum'},
          {label: '账号', name: 'loginName'},
          {label: '密码', name: 'passwordName'},
          {label: '角色', name: 'name'},
          {label: '状态', name: 'isUsedName'},
          {label: '创建时间', name: 'createTime', sortable: true}
        ],
        page: {
          pageNum: 1,
          pageSize: 10,
          total: 1,
          pages: 1
        },
        accountDialog: false,
        accountForm: {
          loginName: '',
          password: '',
          roleId: '',
          isUsed: ''
        },
        rules: { // 表单规则
          loginName: [
            { required: true, message: '请输入账号', toggle: 'blur' },
            { min: 2, max: 30, message: '长度在2-30之间', toggle: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', toggle: 'blur' },
            { min: 2, max: 30, message: '长度在2-30之间', toggle: 'blur' }
          ],
          roleId: [
            { required: true, message: '请选择角色', toggle: 'blur' }
          ],
          isUsed: [
            { required: true, message: '请选择状态', toggle: 'blur' }
          ]
        },
        roleOptions: [], // 角色列表
        workOptions: [ // 启用禁用options
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 }
        ]
      }
    },
    components: {crumbList},
    mounted () {
      this.result()
      this.getRoleList()
    },
    methods: {
      // 查询
      result (searchData) {
        let that = this
        let url = that.api.account.result
        let store = that.$store
        ajax.get(url, searchData || {}, store, true).then((res) => {
          if (res.msg.code === '20000') {
            let data = res.data.list
            let page = res.data.page
            that.page = copyObject(page)
            for (let i = 0; i < data.length; i++) {
              data[i].passwordName = '******'
              data[i].edit = false
              data[i].orderNum = i + 1
              data[i].isUsedName = workType(data[i].isUsed)
            }
            that.tableData = data
          }
        })
      },
      search () { // 搜索
        this.searchData.pageNum = 1
        this.result(this.searchData)
      },
      // 重置
      reset () {
        this.searchData = {
          loginName: ''
        }
      },
      // 新增账号
      submitForm (formName) {
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.account.add

        that.$refs[formName].validate((valid) => {
          if (valid) { // 通过验证
            this.$mb('确认提交吗？', '提示').then(() => {
              that.accountForm.creater = sessionStorage.getItem('accountId')
              ajax.post(url, that.accountForm, store).then((res) => {
                let code = res.msg.code
                let data = res.data
                data.edit = false
                data.id = res.data.id
                data.name = getRoleName(that.accountForm.roleId, that.roleOptions)
                data.passwordName = '******'
                data.isUsedName = workType(res.data.isUsed)
                if (code === '20000') {
                  msg({type: 'success', message: '新增成功'})
                  that.tableData.unshift(data)
                  that.accountDialog = false
                } else {
                  msg({type: 'error', message: res.msg.message})
                }
                store.dispatch('setLoading', false)
              }).catch((err) => {
                if (err) throw err
                store.dispatch('setLoading', false)
                msg({type: 'error', message: '网络异常'})
              })
            }).catch(() => {})
          } else { // 未通过验证
            console.log('error')
          }
        })
      },
      // 修改
      handleUpdate (index, row) {
        row.edit = false
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.account.update
        this.$mb('确认修改吗？', '提示').then(() => {
          row.modifier = sessionStorage.getItem('accountId')
          store.dispatch('setLoading', true)
          ajax.post(url, row, store).then((res) => {
            if (res.msg.code === '20000') {
              msg({type: 'success', message: '编辑成功'})
              row.isUsedName = workType(row.isUsed)
              row.name = getRoleName(row.roleId, that.roleOptions)
              row.edit = false
            } else {
              msg({type: 'error', message: res.msg.message})
            }
            store.dispatch('setLoading', false)
          }).catch((err) => {
            if (err) throw err
            store.dispatch('setLoading', false)
            msg({type: 'error', message: '网络异常'})
          })
        }).catch(() => {})
      },
      // 删除
      remove (index, row) {
        let that = this
        let store = that.$store
        let msg = that.$message
        let url = that.api.account.delete
        this.$mb('此操作将删除这个账号, 是否继续?', '提示').then(() => {
          store.dispatch('setLoading', true)
          ajax.post(url, { id: row.id }, store).then((res) => {
            if (res.msg.code === '20000') {
              msg({type: 'success', message: '删除成功'})
              that.tableData.splice(index, 1)
            } else {
              msg({type: 'error', message: res.msg.message})
            }
            store.dispatch('setLoading', false)
          }).catch((err) => {
            console.log(err)
            store.dispatch('setLoading', false)
            msg({type: 'error', message: '网络异常'})
          })
        }).catch(() => {})
      },
      handleCurrentChange (val) {
        this.searchData.pageNum = val
        this.result(this.searchData)
      },
      dialogFormClose (formName) { // 关闭新增弹窗
        this.$refs[formName].resetFields()
        this.accountDialog = false
      },
      getRoleList () {
        let url = this.api.role.result
        let store = this.$store
        ajax.get(url, {}, store, true).then((res) => {
          let data = res.list
          this.roleOptions = data
        })
      }
    }
  }
</script>
